﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Surface;
using Microsoft.Surface.Presentation;
using Microsoft.Surface.Presentation.Controls;
using Microsoft.Surface.Presentation.Input;
using navigation.Helpers;
using System.Collections.ObjectModel;
using navigation.Data;



namespace navigation
{
    /// <summary>
    /// Interaction logic for SurfaceWindow1.xaml
    /// </summary>
    public partial class SurfaceWindow1 : SurfaceWindow
    {
        # region data initialize
        private ObservableCollection<UserStory> productBacklogItems;

        private ObservableCollection<UserStory> sprintBacklogItems;

        public ObservableCollection<UserStory> ProductBacklogItems
        {
            get
            {
                if (productBacklogItems == null)
                {
                    productBacklogItems = new ObservableCollection<UserStory>();
                }

                return productBacklogItems;
            }
        }

        public ObservableCollection<UserStory> SprintBacklogItems
        {
            get
            {
                if (sprintBacklogItems == null)
                {
                    sprintBacklogItems = new ObservableCollection<UserStory>();
                }

                return sprintBacklogItems;
            }
        }

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);
            DataContext = this;
            ObservableCollection<Task> agileBoard = new ObservableCollection<Task>();
            agileBoard.Add(new Task("Add rows", "agile board", "Add rows to contain all the user story in Sprint Backlog", "Done"));
            agileBoard.Add(new Task("Add story cards", "agile board", "", "Done"));
            agileBoard.Add(new Task("Allow swrap task cards", "agile board", "", "Done"));

            ProductBacklogItems.Add(new UserStory("agile board", "done", "As a Scrum master, I need a agile board to manage all the stories and tasks", 20, agileBoard));
            ProductBacklogItems.Add(new UserStory("product backlog", "planned", "As a Scrum master, I need a product backlog to store all the user stories"));
            ProductBacklogItems.Add(new UserStory("sprint backlog", "planned", "As a Scrum master, I need a sprint backlog to determine each iteration work and add task cards"));
            ProductBacklogItems.Add(new UserStory("burn down chart", "planned", "As a Scrum master, I need a burn down chart to show the development progress"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));
            ProductBacklogItems.Add(new UserStory("Test item", "planned", "Test item"));

            ObservableCollection<Task> testItems1 = new ObservableCollection<Task>();
            testItems1.Add(new Task("Task 1", "Test item 1", "", "Planned"));
            testItems1.Add(new Task("Task 2", "Test item 1", "", "Planned"));
            testItems1.Add(new Task("Task 3", "Test item 1", "", "Planned"));
            testItems1.Add(new Task("Task 4", "Test item 1", "", "Planned"));

            ObservableCollection<Task> testItems2 = new ObservableCollection<Task>();
            testItems2.Add(new Task("Task 1", "Test item 2", "", "Planned"));
            testItems2.Add(new Task("Task 2", "Test item 2", "", "InProgress"));
            testItems2.Add(new Task("Task 3", "Test item 2", "", "InProgress"));
            testItems2.Add(new Task("Task 4", "Test item 2", "", "Done"));
           
            SprintBacklogItems.Add(new UserStory("Test item 1", "inprogress", "Test item", 15, testItems1));
            SprintBacklogItems.Add(new UserStory("Test item 2", "inprogress", "Test item", 20, testItems2));
            
        }

        protected override void OnPreviewTouchDown(TouchEventArgs e)
        {
            bool isFingerRecognized = e.TouchDevice.GetIsFingerRecognized();
            bool isTagRecognized = e.TouchDevice.GetIsTagRecognized();            
            if (isFingerRecognized == false && isTagRecognized == false)
            {
                e.Handled = true;
                return;
            }
            base.OnPreviewTouchDown(e);
        }

        # endregion

        public static readonly RoutedCommand MainMenuCommand = new RoutedCommand("MainMenu", typeof(SurfaceWindow1));
        //private Collection<TouchDevice> currentTouchDevices = new Collection<TouchDevice>();
        private Dictionary<TouchDevice, Point> currentTouchDevices = new Dictionary<TouchDevice, Point>();

        /// <summary>
        /// Default constructor.
        /// </summary>
        public SurfaceWindow1()
        {
            InitializeComponent();
            //UpdateBackground();
            if (!SurfaceEnvironment.IsSurfaceEnvironmentAvailable)
            {
                // running in simulator.
                //Startup();
            }           

            // Add handlers for window availability events
            AddWindowAvailabilityHandlers();
            MouseTouchDevice.RegisterEvents(this);
            SetupMenuCommand();
        }

        private void UpdateBackground()
        {
            _layoutRoot.Background = Resources["HorizontalBackground"] as ImageBrush;
			(Resources["ShowActivated"] as Storyboard).Begin(this);
        }

        public void Startup()
        {
            // Fade the app in so that the loading message appears on the correct side before the user sees it.
            (Resources["ShowActivated"] as Storyboard).Begin(this);
        }

        /// <summary>
        /// Occurs when the window is about to close. 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            // Remove handlers for window availability events
            RemoveWindowAvailabilityHandlers();
        }

        /// <summary>
        /// Adds handlers for window availability events.
        /// </summary>
        private void AddWindowAvailabilityHandlers()
        {
            // Subscribe to surface window availability events
            ApplicationServices.WindowInteractive += OnWindowInteractive;
            ApplicationServices.WindowNoninteractive += OnWindowNoninteractive;
            ApplicationServices.WindowUnavailable += OnWindowUnavailable;
        }

        /// <summary>
        /// Removes handlers for window availability events.
        /// </summary>
        private void RemoveWindowAvailabilityHandlers()
        {
            // Unsubscribe from surface window availability events
            ApplicationServices.WindowInteractive -= OnWindowInteractive;
            ApplicationServices.WindowNoninteractive -= OnWindowNoninteractive;
            ApplicationServices.WindowUnavailable -= OnWindowUnavailable;
        }

        /// <summary>
        /// This is called when the user can interact with the application's window.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnWindowInteractive(object sender, EventArgs e)
        {
            //TODO: enable audio, animations here
        }

        /// <summary>
        /// This is called when the user can see but not interact with the application's window.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnWindowNoninteractive(object sender, EventArgs e)
        {
            //TODO: Disable audio here if it is enabled

            //TODO: optionally enable animations here
        }

        /// <summary>
        /// This is called when the application's window is not visible or interactive.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnWindowUnavailable(object sender, EventArgs e)
        {
            //TODO: disable audio, animations here
        }

        //private void ButtonPreviousPage_Click(object sender, RoutedEventArgs e)
        //{
        //    NavigationPanel.Previous();
        //}


        //private void ButtonNextPage_Click(object sender, RoutedEventArgs e)
        //{
        //    NavigationPanel.Next();
        //}

        //private void exitButton_Click(object sender, RoutedEventArgs e)
        //{
        //    Application.Current.Shutdown();
        //}

        

        private void SetupMenuCommand()
        {
            CommandBinding processMenuCommand = new CommandBinding(MainMenuCommand, ProcessMenuCommand, null);
            this.CommandBindings.Add(processMenuCommand);
        }

        private void ProcessMenuCommand(object sender, ExecutedRoutedEventArgs args)
        {
            Console.WriteLine(args.Parameter.ToString());
            if ((string)args.Parameter == "PreviousPage")
            {
                if(NavigationPanel.PreviousIsValid)
                    NavigationPanel.Previous();
            }
            else if ((string)args.Parameter == "NextPage")
            {
                if(NavigationPanel.NextIsValid)
                    NavigationPanel.Next();
            }
            else
            {
                Application.Current.Shutdown();
            }
        }

        private void NavigationPanel_TouchDown(object sender, TouchEventArgs e)
        {
            if (e.TouchDevice.GetIsFingerRecognized())
                currentTouchDevices.Add(e.TouchDevice, e.TouchDevice.GetPosition(this));
        }

        private void NavigationPanel_TouchUp(object sender, TouchEventArgs e)
        {
            currentTouchDevices.Remove(e.TouchDevice);        
        }

        private void NavigationPanel_TouchMove(object sender, TouchEventArgs e)
        {
            if (currentTouchDevices.Count == 3 || currentTouchDevices.Count == 4)
            {
                int isLeft = 0;
                int isRight = 0;
                foreach (KeyValuePair<TouchDevice, Point> td in currentTouchDevices)
                {
                    if (td.Key != null && e.TouchDevice.GetPosition(this).X - td.Value.X > 100 && e.TouchDevice.GetPosition(this).Y - td.Value.Y < 50 && e.TouchDevice.GetPosition(this).Y - td.Value.Y > -50)
                        isRight++;
                    else if (td.Key != null && td.Value.X - e.TouchDevice.GetPosition(this).X > 100 && e.TouchDevice.GetPosition(this).Y - td.Value.Y < 50 && e.TouchDevice.GetPosition(this).Y - td.Value.Y > -50)
                        isLeft++;
                    else
                        return;
                }

                if (isLeft >= 3 && isRight == 0)
                {
                    if (NavigationPanel.NextIsValid)
                    {
                        NavigationPanel.Next();
                        currentTouchDevices.Clear();
                        return;
                    }
                }

                if (isLeft == 0 && isRight >= 3)
                {
                    if (NavigationPanel.PreviousIsValid)
                    {
                        NavigationPanel.Previous();
                        currentTouchDevices.Clear();
                        return;
                    }
                }

            }
        }

        private void SlideSwitch_PreviewTouchDown(object sender, TouchEventArgs e)
        {
            if (SlideSwitch.btnValue == "Left")
            {
                if (NavigationPanel.PreviousIsValid)
                {
                    NavigationPanel.Previous();
                    return;
                }
            }
            else if (SlideSwitch.btnValue == "Right")
            {
                if (NavigationPanel.NextIsValid)
                {
                    NavigationPanel.Next();
                    return;
                }
            }
            else
                return;
        }

        
    }
}